const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs').promises
const { body, validationResult } = require('express-validator')
const { query: dbQuery, transaction } = require('../config/database')
const { authenticateToken, requireAdmin } = require('../middleware/auth')
const bcrypt = require('bcryptjs')
const config = require('../config')

const router = express.Router()

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../uploads/'))
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
    cb(
      null,
      file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)
    )
  }
})

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024 // 50MB限制
  },
  fileFilter: function (req, file, cb) {
    if (file.fieldname === 'userData') {
      // 用户数据支持JSON格式
      if (
        file.mimetype === 'application/json' ||
        path.extname(file.originalname) === '.json'
      ) {
        cb(null, true)
      } else {
        cb(new Error('用户数据文件必须是JSON格式'))
      }
    } else {
      cb(new Error('不支持的文件类型'))
    }
  }
})

/**
 * @swagger
 * /api/admin/import-users:
 *   post:
 *     summary: 批量导入用户数据
 *     tags: [管理员]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               userData:
 *                 type: string
 *                 format: binary
 *                 description: 用户数据JSON文件
 *     responses:
 *       200:
 *         description: 导入成功
 */
router.post(
  '/import-users',
  authenticateToken,
  requireAdmin,
  upload.single('userData'),
  async (req, res, next) => {
    try {
      if (!req.file) {
        return res.error('请上传用户数据文件', 'FILE_REQUIRED')
      }

      // 读取上传的JSON文件
      const fileContent = await fs.readFile(req.file.path, 'utf8')
      const userData = JSON.parse(fileContent)

      if (!Array.isArray(userData)) {
        return res.error('用户数据必须是数组格式', 'INVALID_DATA_FORMAT')
      }

      let importedCount = 0
      let errorCount = 0
      const errors = []

      // 批量处理用户数据
      for (const user of userData) {
        try {
          await transaction(async connection => {
            // 验证必需字段
            if (!user.email || !user.username || !user.password) {
              throw new Error(`用户 ${user.email || 'unknown'} 缺少必需字段`)
            }

            // 检查邮箱是否已存在
            const [existingUser] = await connection.execute(
              'SELECT id FROM users WHERE email = ?',
              [user.email]
            )

            if (existingUser.length > 0) {
              throw new Error(`邮箱 ${user.email} 已存在`)
            }

            // 加密密码
            const hashedPassword = await bcrypt.hash(
              user.password,
              config.security.bcryptSaltRounds
            )

            // 插入用户数据
            await connection.execute(
              `
              INSERT INTO users (
                email, username, password, avatar, is_vip, vip_expires_at, 
                coins, reading_time, created_at, updated_at
              ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            `,
              [
                user.email,
                user.username,
                hashedPassword,
                user.avatar || null,
                user.is_vip || false,
                user.vip_expires_at || null,
                user.coins || 0,
                user.reading_time || 0
              ]
            )

            importedCount++
          })
        } catch (error) {
          errorCount++
          errors.push(error.message)
        }
      }

      // 删除临时文件
      await fs.unlink(req.file.path)

      res.success(
        {
          importedCount,
          errorCount,
          errors: errors.slice(0, 10) // 只返回前10个错误
        },
        `用户数据导入完成，成功导入 ${importedCount} 个用户`
      )
    } catch (error) {
      // 清理临时文件
      if (req.file) {
        try {
          await fs.unlink(req.file.path)
        } catch (unlinkError) {
          console.error('删除临时文件失败:', unlinkError)
        }
      }
      next(error)
    }
  }
)

/**
 * @swagger
 * /api/admin/import-novel:
 *   post:
 *     summary: 导入小说文件
 *     tags: [管理员]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               novelFile:
 *                 type: string
 *                 format: binary
 *                 description: 小说TXT文件
 *               title:
 *                 type: string
 *                 description: 小说标题
 *               author:
 *                 type: string
 *                 description: 作者名称
 *               description:
 *                 type: string
 *                 description: 小说描述
 *               category:
 *                 type: string
 *                 description: 分类
 *               coverUrl:
 *                 type: string
 *                 description: 封面图片URL
 *               freeChapters:
 *                 type: integer
 *                 description: 免费章节数
 *               vipPrice:
 *                 type: integer
 *                 description: VIP章节价格
 *     responses:
 *       200:
 *         description: 导入成功
 */

/**
 * @swagger
 * /api/admin/export-users:
 *   get:
 *     summary: 导出用户数据
 *     tags: [管理员]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 导出成功
 */
router.get(
  '/export-users',
  authenticateToken,
  requireAdmin,
  async (req, res, next) => {
    try {
      const users = await dbQuery(`
      SELECT 
          email, username, avatar, is_vip, vip_expires_at,
          coins, reading_time, created_at
        FROM users
      ORDER BY created_at DESC
      `)

      res.setHeader('Content-Type', 'application/json')
      res.setHeader('Content-Disposition', 'attachment; filename=users.json')
      res.send(JSON.stringify(users, null, 2))
    } catch (error) {
      next(error)
    }
  }
)

/**
 * 解析TXT文件为章节数据
 */

/**
 * @swagger
 * /api/admin/database-stats:
 *   get:
 *     summary: 获取数据库统计信息
 *     tags: [管理员]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 */
router.get(
  '/database-stats',
  authenticateToken,
  requireAdmin,
  async (req, res, next) => {
    try {
      const userStats = await dbQuery('SELECT COUNT(*) as total FROM users')
      const novelStats = await dbQuery('SELECT COUNT(*) as total FROM novels')
      const chapterStats = await dbQuery(
        'SELECT COUNT(*) as total FROM chapters'
      )
      const vipUserStats = await dbQuery(
        'SELECT COUNT(*) as total FROM users WHERE is_vip = true'
      )

      res.success(
        {
          users: userStats.total,
          novels: novelStats.total,
          chapters: chapterStats.total,
          vipUsers: vipUserStats.total
        },
        '统计信息获取成功'
      )
    } catch (error) {
      next(error)
    }
  }
)

module.exports = router
